#!/bin/sh

# date needs to use C for date (LC_TIME) formatting, so ensure it's
# not overridden.
export LANGUAGE=C
export LANG=C
export LC_TIME=C
export LC_ALL=C

PACKAGE="$(sed -ne '/^Welcome to /{s/Welcome to[[:space:]][[:space:]]*\([[:alnum:]][[:alnum:]]*\)[[:space:]][[:space:]]*\([[:alnum:]][[:alnum:].-]*\)\..*/\1/p;q}' < NEWS)"
VERSION="$(sed -ne '/^Welcome to /{s/Welcome to[[:space:]][[:space:]]*\([[:alnum:]][[:alnum:]]*\)[[:space:]][[:space:]]*\([[:alnum:]][[:alnum:].-]*\)\..*/\2/p;q}' < NEWS)"

TAG="release/${PACKAGE}-${VERSION}"
COMMIT="$(git rev-parse "$TAG^{}" 2>/dev/null)" || COMMIT=""

if [ -n "$COMMIT" ]; then
    COMMIT_DATE="$(git log -1 "$COMMIT" --pretty="format:%ai")"

    RELEASE_DATE="$(date --date="$COMMIT_DATE" '+%d %b %Y')"
    RELEASE_BY="$(git show "$TAG" | sed -ne '/^Tagger:/{s/Tagger:[[:space:]][[:space:]]*//p;q}')"
else
    RELEASE_DATE="$(date '+%d %b %Y')"
    RELEASE_BY="Unreleased"
fi
RELEASE_DATE_UNIX=$(date +%s --date="$RELEASE_DATE")


cat << EOF
set(GIT_RELEASE_PACKAGE "$PACKAGE")
set(GIT_RELEASE_VERSION "$VERSION")
set(GIT_RELEASE_DATE "$RELEASE_DATE")
set(GIT_RELEASE_DATE_UNIX "$RELEASE_DATE_UNIX")
set(GIT_RELEASE_BY "$RELEASE_BY")
EOF

if [ -n "$COMMIT" ]; then
  cat << EOF
set(GIT_RELEASE_TAG "$TAG")
EOF
fi
